package com.elm.service.impl;

import com.elm.controller.BusinessController;
import com.elm.mapper.BusinessMapper;
import com.elm.mapper.FoodMapper;
import com.elm.mapper.UserMapper;
import com.elm.po.Authority;
import com.elm.po.Business;
import com.elm.po.Food;
import com.elm.po.User;
import com.elm.service.BusinessService;
import com.elm.service.UserService;
import com.elm.util.JwtUtil;

import jakarta.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;

@Service
public class BusinessServiceImpl implements BusinessService {


    @Autowired
    private BusinessMapper businessMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private FoodMapper foodMapper;
    @Autowired
    private UserService userService; // 用于验证用户存在性
    @Autowired
    private HttpServletRequest request;


    // 公共方法：从Token获取当前用户ID
    private String getCurrentUserName() {
        String token = (String) request.getAttribute("token");
        return JwtUtil.getUsernameFromToken(token);
    }

    // 公共方法：从Token获取当前用户类型
    private String getCurrentUserType() {
        String token = (String) request.getAttribute("token");
        return JwtUtil.getUserTypeFromToken(token);
    }

    @Override
    public List<Business> getBusinessByOrderTypeId(Integer orderTypeId) {
        // 无需权限验证，公开接口
        return businessMapper.getBusinessByOrderTypeId(orderTypeId);
    }

    @Override
    public Business getBusinessById(Integer businessId) {
        // 无需权限验证，公开接口
        return businessMapper.getBusinessById(businessId);
    }

    @Override
    public List<Business> getBusinessBySales() {
        // 按销量排序，仅查询营业中商家
        return businessMapper.getBusinessBySales();
    }

    @Override
    public List<Business> getBusinessByStar() {
        // 按评分排序
        return businessMapper.getBusinessByStar();
    }

    @Override
    public List<Business> getAllReviewingBusiness() {
    	System.out.println(getCurrentUserType());
        // 验证当前用户是否为ADMIN
        if (!"ADMIN".equals(getCurrentUserType())) {
            throw new RuntimeException("权限不足：仅管理员可查看待审核商家");
        }
        return businessMapper.getAllReviewingBusiness();
    } 

    @Override
    public Business updateBusinessStatus(Integer businessId, String result) {          //集成各方权限判断
    	User user = userMapper.getUserByName(getCurrentUserName()); 
		if ("USER".equals(getCurrentUserType()) && !userMapper.getStaffWorkByStaffId(user.getId()).contains(businessId)) {         //排除普通USER
			throw new RuntimeException("权限不足：仅商家老板或staff或ADMIN可修改status信息");
		}
		if("USER".equals(getCurrentUserType()) && !result.equals("opening") && !result.equals("closing")) {           //staff仅可修改这两项
			throw new RuntimeException("权限不足：staff无权修改其他属性");
		}
		if ("BUSINESS".equals(getCurrentUserType())) {
			User boss = userMapper.getUserByName(getCurrentUserName());
			List<Business> businessList = businessMapper.getBusinessListByUserId(boss.getId());
			boolean isAssociated = businessList.stream()
					.anyMatch(biz -> biz.getId().equals(businessId));
			if (!isAssociated) {
				throw new RuntimeException("错误：老板未关联此商家");
			}
		}
		if("BUSINESS".equals(getCurrentUserType()) && !result.equals("closing") && !result.equals("opening") &&!result.equals("offline")) {     //boss可下线
			throw new RuntimeException("权限不足：boss无权修改其他属性");
		}
		if( "BUSINESS".equals(getCurrentUserType()) &&( businessMapper.getBusinessById(businessId).getBusinessStatus().equals("banned") || businessMapper.getBusinessById(businessId).getBusinessStatus().equals("offline"))) {
			throw new RuntimeException("权限不足：已下线和封禁商家无权修改商铺信息");
		}
        businessMapper.updateBusinessStatus(businessId, result);
        return businessMapper.getBusinessById(businessId);
    }
    
    
    // 商家Boss专属：创建商家（发起开店请求）
    @Override
    public int createBusiness(Business business) {
        String userType = getCurrentUserType();
        String userName = getCurrentUserName();
        if (!"ADMIN".equals(userType) && !"BUSINESS".equals(userType)) {
            throw new RuntimeException("权限不足：仅ADMIN或boss可发起开店请求");
        }
        if("BUSINESS".equals(userType) && business.getBusinessOwner().getId()!=userMapper.getUserIdByName(userName)) {
        	throw new RuntimeException("权限不足：仅支持本人操作");
        }
        if(businessMapper.getBusinessByName(business.getBusinessName())!=null)
        {
        	throw new RuntimeException("错误：店名重复");
        }
        User businessOwner = business.getBusinessOwner();
        business.setUserId(businessOwner.getId());
        
        return businessMapper.createBusiness(business);
    }
    

    // 商家Boss专属：更新商家信息
    @Override 
    public Business updateBusiness(Business business,Integer id) {
    	String userType = getCurrentUserType();
    	if (!"ADMIN".equals(userType) && !"BUSINESS".equals(userType)) {
            throw new RuntimeException("权限不足：仅ADMIN或boss可更新");
        }
    	if( "BUSINESS".equals(getCurrentUserType()) &&( businessMapper.getBusinessById(id).getBusinessStatus().equals("banned") || businessMapper.getBusinessById(id).getBusinessStatus().equals("offline"))) {
			throw new RuntimeException("权限不足：已下线和封禁商家无权修改商铺信息");
		}
    	business.setId(id);
    	businessMapper.updateBusiness(business);
        return businessMapper.getBusinessById(id);
    }


	@Override
	public Business getBusinessByName(String business_name) {
		return businessMapper.getBusinessByName(business_name);
	}

	@Override
	public List<Business> getAllBusiness() {
		return  businessMapper.getAllBusiness();
	}

	@Override
	public List<Business> getBusinessByBoss(Integer userId) {
    	User user = userMapper.getUserByName(getCurrentUserName()); 
		if(userId!=user.getId() && !"admin".equals(getCurrentUserType())) {
			throw new RuntimeException("权限不足：仅本人和admin可查看信息");
		}
		return businessMapper.getBusinessListByUserId(userId);
	}

}